<template>
    <div>
        <!-- 分类列表视图 -->
        <div v-show="activeStatu">
            <el-card class="box">
                <div class="card-content">
                    <!-- 搜索区域 -->
                    <div class="search-header flex">
                        <div class="search-title">分类标题</div>
                        <div class="time_top">创建时间</div>
                    </div>
                    <div class="search-fields flexBox">
                        <!-- 标题搜索输入框 -->
                        <div class="search-input-container"> 
                            <el-input v-model.trim="inputed" @input="filters" placeholder="输入内容">
                                <template #prefix>
                                    <el-icon class="el-input__icon">
                                        <search />
                                    </el-icon>
                                </template>
                            </el-input>
                        </div>
                        <!-- 日期范围选择器 -->
                        <div class="date-picker-container">
                            <el-date-picker @change="data_filters" v-model="time" type="daterange"
                                range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" />
                        </div>
                    </div>
                    <!-- 操作按钮区域 -->
                    <div class="action-buttons">
                        <div><el-button type="primary" @click="add" class="add_class">
                                新增</el-button>
                        </div>
                        <el-button type="danger" class="delelist"
                            @click="deleList">批量删除</el-button>
                    </div>
                    <!-- 分类数据表格 -->
                    <div class="table-container"> 
                        <el-table :data="activeList.slice((currentPage - 1) * pageSize, currentPage * pageSize)"
                                :cell-style="{ 'text-align': 'center' }" lazy="true"
                                v-el-table-infinite-scroll="handleTableScroll"
                                :header-cell-style="{ 'text-align': 'center' }" @selection-change="handleSelectionChange">
                            <el-table-column type="selection" fixed="left" />
                            <el-table-column prop="id" label="序号" fixed="left" />
                            <el-table-column prop="title" label="标题" show-overflow-tooltip />
                            <el-table-column prop="createtime" label="创建时间" />
                            <el-table-column label="操作" width="250" fixed="right">
                                <template #default="scope">
                                    <div class="handle">
                                        <div @click="edit(scope.row)" class="edit-action">编辑</div>
                                        <div class="action-spacer"></div>
                                        <div @click="deletes(scope.row)" class="delete-action">删除</div>
                                    </div>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                    <!-- 分页控件 -->
                    <div class="paging">
                        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                            :page-sizes="[5, 10, 20, 50]" :small="small" :disabled="disabled" background
                            layout="total, sizes, prev, pager, next, jumper" :total="activeList.length" />
                    </div>

                    <!-- 删除确认对话框 -->
                    <el-dialog title="删除" v-model="centerDialogVisible" width="30%" center>
                        <div class="dialog-message">确认删除该数据吗?</div>
                        <div class="dialog-buttons">
                            <el-button @click="centerDialogVisible = false">取 消</el-button>
                            <el-button type="primary" @click="deleteid">确 定</el-button>
                        </div>
                    </el-dialog>
                    
                    <!-- 未使用的对话框 -->
                    <el-dialog v-model="shows" title="是否要删除" center width="20vw">
                        <el-button @click="shows = false">取 消</el-button>
                        <el-button type="primary" @click="oks">确 定</el-button>
                    </el-dialog>
                    
                    <!-- 批量删除确认对话框 -->
                    <el-dialog title="批量删除" v-model="centerDialogVisiblet" width="30%" center>
                        <div class="dialog-message">确认删除这批数据吗?</div>
                        <span slot="footer" class="dialog-footer">
                            <div></div>
                            <div>
                                <el-button @click="centerDialogVisiblet = false">取 消</el-button>
                                <el-button type="primary" @click="deleteid_t">确 定</el-button>
                            </div>
                        </span>
                    </el-dialog>
                </div>
            </el-card>
        </div>

        <!-- 新增/编辑分类表单视图 -->
        <div v-show="activeStatud" class="form-container">
            <el-card class="form-card">
                <div class="form-header">{{ addText }}</div>
                <div class="form-divider"></div>
                <!-- 表单区域 -->
                <div class="form-content">
                    <el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules"
                        label-position="left" label-width="auto" class="demo-ruleForm">
                        <el-form-item label="分类名称" prop="title">
                            <el-input v-model.trim="ruleForm.title" placeholder="请输入" />
                        </el-form-item>
                    </el-form>
                    <!-- 表单操作按钮 -->
                    <div class="form-actions">
                        <el-button type="primary" @click="submitForm(ruleFormRef)">确认</el-button>
                        <el-button @click="closes(ruleFormRef)">取消</el-button>
                    </div>
                </div>
            </el-card>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
// 导入API接口
import { typeList, typeSave, typeDel } from '../../../api/shopClass/index';
import { ElMessage, ElCard, } from 'element-plus';
import { useRouter } from 'vue-router';

// 数据筛选条件
const time = ref('')
// 分类数据列表
const activeList = ref([]);
// 视图状态控制
const activeStatu = ref(true)
const activeStatud = ref(false)
const names = ref('导出');
// 注入外部函数和变量
import { inject } from 'vue'
const testFn = inject('testFn')
testFn()
const testName = inject('testName')
const dialogTableVisible = ref(false);
// 状态标识(1:新增,2:编辑)
const statused = ref('1');
const router = useRouter();
// 表格分页控制
const inputed = ref('');
const inputeds = ref('');
const pageSize = ref(5);
const currentPage = ref(1);
const pageSizes = ref(5);
const currentPages = ref(1);
const copyList = ref([]);
const files = ref(false);
const synopsiss = ref('请输入简介')
// 当前操作的ID
const activId = ref('')
// 用户token
let tokens = JSON.parse(localStorage.getItem('tokens'));
console.log(tokens);

// 初始化加载分类数据
render();
function render() {
    typeList().then((res) => {
        console.log(res);
        activeList.value = res.data;
        copyList.value = res.data;
    });
}

// 表单初始数据
const ruleForms = reactive({
    title: ''
})

const list = ref([])
const lists = ref([])

// 新增分类
const addText = ref("")
function add() {
    Object.assign(ruleForm, ruleForms)
    activeStatu.value = false
    addText.value = '添加'
    activeStatud.value = true
    dialogTableVisible.value = true;
    statused.value = '1';
    disableds.value = true;
    // 重置表单数据
    ruleForm.name = '', 
    ruleForm.start_time = '', 
    ruleForm.end_time = '', 
    ruleForm.details = '', 
    ruleForm.img = '', 
    ruleForm.synopsis = '';
}

// 表单数据和验证规则
const ruleForm = reactive({
    title: '',
});
const ruleFormRef = ref('');
const rules = reactive({
  title: [
    {
      required: true,
      message: '请输入分类名称',
      trigger: 'blur',
    },
    {
      validator: (rule, value, callback) => {
        if (value) {
          // 检查输入的内容是否已存在于 activeList 中
          const isExist = activeList.value.some(item => item.title === value);
          if (isExist) {
            callback(new Error('请勿重复添加'));
          } else {
            callback();
          }
        } else {
          callback();
        }
      },
      trigger: 'blur',
    },
  ],
});

// 表单验证函数(未使用)
function validateEmailDomain(rule, value, callback) {
    if (value === '') {
        callback(new Error('结束时间不能为空'));
    } else if (value < ruleForm.start_time) {
        callback(new Error('结束时间不能小于开始时间'));
    } else {
        callback();
    }
}

const imgUrls = ref('');

// 表单提交处理
const submitForm = (formEl) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      if (statused.value == '1') {
        // 新增分类
        ruleForm.img = imgUrls.value;
        console.log(ruleForm);
        typeSave(ruleForm).then((res) => {
          if (res.code == '1') {
            ElMessage({
              message: '新增成功',
              type: 'success',
            });
            setTimeout(() => {
              activeStatud.value = false;
              activeStatu.value = true;
            }, 1200);
            render();
          }
        });
      } else if (statused.value == '2') {
        // 编辑分类
        ruleForm.id = ids.value;
        typeSave(ruleForm).then((res) => {
          if (res.code == '1') {
            ElMessage({
              message: '编辑成功',
              type: 'success',
            });
            setTimeout(() => {
              activeStatud.value = false;
              activeStatu.value = true;
            }, 1200);
            render();
          } else {
            ElMessage({
              message: '编辑失败，不能和原数据一致',
              type: 'warning',
            });
          }
        });
      }
    } else {
      ElMessage({
        message: '新增失败',
        type: 'error',
      });
    }
  });
};

// 当前编辑项ID
const ids = ref('');
const disableds = ref(true);

// 关闭表单
const closes = (formEl) => {
    console.log(formEl);
    activeStatu.value = true
    activeStatud.value = false
    formEl.resetFields();
    formEl.clearValidate()
    dialogTableVisible.value = false;
    files.value = false;
    ruleForm.name = ''
};

// 编辑分类
function edit(item) {
    Object.assign(ruleForm, item);
    addText.value = '编辑'
    ids.value = item.id;
    activeStatud.value = true
    activeStatu.value = false
    ruleForm.name = item.title
    disableds.value = false;
    statused.value = '2';
}

// 删除分类
function deletes(item) {
    console.log(item);
    centerDialogVisible.value = true;
    deleteids.value = item.id;
}

// 删除ID
const deleteids = ref('');
const centerDialogVisible = ref(false);

// 确认删除
function deleteid() {
    typeDel({
        ids: deleteids.value,
    }).then((res) => {
        if (res.code == '1') {
            centerDialogVisible.value = false;
            ElMessage({
                message: '删除成功',
                type: 'success',
            });
            render();
        }
    });
}

// 标题搜索过滤
function filters() {
    currentPage.value = 1
    console.log(inputed.value);
    let a = [];
    activeList.value = copyList.value.filter(function (item) {
        // 判断是否满足搜索条件
        if (String(item.title).indexOf(String(inputed.value)) > -1) {
            return a;
        }
    });
    currentPage.value = 1
}

// 日期范围搜索过滤
const data_filters = () => {
    let end_time
    let start_time
    let ars = []
    if (time.value) {
        end_time = Date.parse(new Date(time.value[0]))
        start_time = Date.parse(new Date(time.value[1]))
    }
    activeList.value = copyList.value.filter((item) => {
        if (item.title ?
            item.title.indexOf(inputed.value) > -1 &&
            (time.value ?
                Date.parse(new Date(`${item.createtime}`)) > end_time &&
                Date.parse(new Date(` ${item.createtime}`)) < start_time : true
            ) : true
        ) {
            return item
        }
        ars.push(item)
    });
}

// 批量删除相关
const shows = ref(false);
const setArr = ref([]);
const multipleTableRef = ref()
const SelectArr = ref([])
const All_Delete = ref([])

// 表格选择变化处理
const handleSelectionChange = (val) => {
    All_Delete.value = []
    SelectArr.value = val
    // 收集选中项ID
    SelectArr.value.forEach(item => {
        All_Delete.value.push(item.id)
    })
    console.log(All_Delete.value);
}

// 批量删除
const centerDialogVisiblet = ref(false)
const st = ref([])
function deleList() {
    st.value = []
    console.log(All_Delete.value);
    st.value.push(All_Delete.value)
    if (All_Delete.value == '') {
        ElMessage({
            message: '请勾选要删除的数据',
            type: 'warning',
        })
    } else {
        centerDialogVisiblet.value = true
    }
}

// 确认批量删除
const deleteid_t = () => {
    typeDel({
        ids: st.value.join(','),
    }).then(res => {
        console.log(res, '删除成功或失败回调');
        centerDialogVisiblet.value = false;
        render();
        ElMessage({
            message: '删除成功',
            type: 'success',
        })
    })
}
</script>

<style>
/* 样式调整 */
.text {
    font-size: 14px;
}

.item {
    margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
    display: table;
    content: '';
}

.clearfix:after {
    clear: both;
}

.box-card {
    display: flex;
    height: 300px;
    width: 90%;
}

.handle {
    display: flex;
    align-items: center;
    justify-content: center;
}

.paging {
    display: flex;
    justify-content: center;
    margin-top: 10px;
    height: 70px;
}

.flex {
    display: flex;
    align-items: center;
    padding-bottom: 10px;
}

.flexBox {
    display: flex;
    width: 100%;
    align-items: center;
}

.el-date-range-picker__content {
    box-sizing: border-box;
    float: left;
    margin: 0;
    padding: 16px;
    width: 38%;
}

/* 提取的内联样式 */
.card-content {
    padding: 10px;
}

.search-header {
    padding-bottom: 10px;
}

.search-title {
    width: 220px;
}

.search-input-container el-input {
    width: 220px;
}

.date-picker-container {
    margin-left: 20px;
}

.date-picker-container el-date-picker {
    width: 220px;
}

.action-buttons {
    display: flex;
}

.table-container {
    margin-top: 10px;
    width: 100%;
    height: auto;
}

.edit-action {
    color: rgba(64, 158, 255, 1);
    cursor: pointer;
}

.delete-action {
    color: red;
    cursor: pointer;
}

.action-spacer {
    width: 10px;
}

.form-container {
    padding: 10px;
}

.form-card {
    width: 96%;
    margin-left: 2%;
    margin-top: 1%;
    position: relative;
    height: 80vh;
}

.form-header {
    padding: 10px;
}

.form-divider {
    width: 100%;
    height: 1px;
    background-color: rgba(195, 195, 195, 1);
}

.form-content {
    margin-top: 20px;
    margin-left: 100px;
    margin-top: 50px;
}

.form-content el-form {
    width: 40%;
}

.form-actions {
    position: absolute;
    bottom: 20px;
    right: 40px;
}

.dialog-message {
    font-size: 16px;
    padding-bottom: 20px;
}

.dialog-buttons {
    display: flex;
    justify-content: end;
}
</style>    